import eventBus from "@/eventBus";
import {
    debounce
} from "@/utils";
import defaultGif from "@/assets/default.gif";

let imgs = [];

function setImage(img) {
    img.dom.src = defaultGif; //先暂时使用默认图片
    //处理图片
    //判断该图片是否处于视口内
    const clientHeight = document.documentElement.clientHeight;
    const rect = img.dom.getBoundingClientRect();
    const height = rect.height || 50;
    if (rect.top >= -height && rect.top <= clientHeight) {
        //在视口内
        img.dom.src = img.src;
        imgs = imgs.filter((i) => i !== img);
    }
}

function setImages() {
    for (const img of imgs) {
        setImage(img);
    }
}

function handleScroll() {
    setImages();
}
eventBus.$on("mainScroll", debounce(handleScroll, 50))


export default {
    inserted(el, bindings) {
        /* 被绑定元素插入父节点时调用 (仅保证父节点存在，但不一定已被插入文档中)。 */
        const img = {
            dom: el,
            src: bindings.value,
        };
        imgs.push(img);

        //立即处理图片
        setImage(img);

    },
    unbind(el) {
        /* 只调用一次，指令与元素解绑时调用。 */
        imgs = imgs.filter((img) => img.dom !== el);
    }
}